/**
 * 系统主页面
 */
Ext.namespace('Divo');
Ext.namespace('Divo.app');
Ext.QuickTips.init();
var uiDcInc;

Divo.app.Main = function() {
  /* -------------------- private属性 -------------------- */
  var aboutWin, menuBar, mainPanel, viewport, pwdWin;
  var sysConfig, thumbTemplate;
  var maxPanelNum = 3;

  /* -------------------- private方法 -------------------- */
  // 创建菜单栏
  function createMenus() {

    menuBar = new Ext.Toolbar({
          id : 'menu-toolbar'
        });

    Ext.Ajax.request({
          url : 'system/load_grant_subsystem',
          success : successFn
        });

  }

  // 关闭全部打开的主面板Tab Panel
  function onCloseMainPanelTabs() {
    var ps = []
    var items = mainPanel.items.items;
    for (var i = 0; i < items.length; i++) {
      ps.push(items[i].id);
    }
    for (var i = 0; i < ps.length; i++) {
      mainPanel.remove(mainPanel.getItem(ps[i]), true);
    }
  }

  // 创建布局
  function createViewport() {

    aboutWin = new Divo.app.AboutWin({
          sysConfig : sysConfig
        });

    pwdWin = new Divo.app.ChangePwdFormWin({
          curUserName : sysConfig.user_name
        });

    var statusBar = new Ext.BoxComponent({
          region : 'south',
          height : 18,
          autoEl : {
            html : '<center>&nbsp;' + sysConfig.copyright + '</center>'
          }
        });

    mainPanel = new Divo.app.MainPanel({
          cfg_run_mode : CFG_DEPLOYMENT_TYPE,
          build_id : CFG_BUILD_ID
        });

    // 限制最多能打开的面板,防止浏览器过载崩溃
    mainPanel.on('beforeadd', function(container, component, index) {
          if (index > maxPanelNum) {
            var items = container.items.items;
            var menuId = items[0].id;
            var tab = mainPanel.getItem(menuId)
            mainPanel.remove(tab, true);
          }
        });

    // 防止IFRAME销毁后仍然占用内存
    mainPanel.on('beforeremove', function(o, p) {
          var _id = p.id.substring(p.id.indexOf('-') + 1);
          var ifrId = "frame-" + _id;

          var wf = window.frames[ifrId];

          // 该方法有效
          if (!Ext.isEmpty(wf)) {
            wf.document.open("text/html", "replace");
            wf.document.write("");
            wf.document.close();
          }

        });

    var titleBar = new Ext.Panel({
      region : 'north',
      id : 'north-panel',
      split : false,
      height : 56,
      border : false,
      collapsible : false,
      margins : '0 0 0 0',
      layout : 'border',
      items : [{
        region : 'north',
        html : '<div id="titlebar"><input type=hidden value="" id="activeFrameId">'
            + '</input><h1>'
            + sysConfig.application_name
            + "-"
            + sysConfig.module_name + '</h1></div>',
        border : false,
        height : 28
      }, {
        region : 'center',
        border : false,
        height : 26,
        items : [menuBar]
      }]
    });

    viewport = new Ext.Viewport({
      layout : 'tdgi_border',
      items : [titleBar, statusBar, mainPanel]
        // menuComponent, mainPanel]

      });

    viewport.doLayout();
  }

  function onItemClick(item, e) {
    if (item.url.length > 0) {
      e.stopEvent();
      mainPanel.loadContent(item.url, item.resourceId, item.text, item.iconCls,
          sysConfig.module_name);
      viewport.doLayout();
    } else {
      e.stopEvent();
    }
  }

  function createNestedMenu(menu, resourceId) {
    Ext.Ajax.request({
          url : 'system/loadmenu',
          async : false,
          params : {
            resourceId : resourceId
          },
          callback : function(o, s, r) {
            var datas = Ext.decode(r.responseText);

            for (var i = 0; i < datas.length; i++) {
              var menuCode = datas[i].resourceId;
              var menuName = datas[i].text;
              var leaf = datas[i].leaf;
              var url = datas[i].url;

              if (leaf) {
                var m = new Ext.menu.Item({
                      id : 'menu-' + menuCode,
                      iconCls : datas[i].iconCls,
                      resourceId : menuCode,
                      text : menuName,
                      url : url,
                      handler : onItemClick
                    });

                menu.add(m);
                // return;
              } else {
                var m = new Ext.menu.Menu({
                      id : 'menu-' + menuCode,
                      iconCls : datas[i].iconCls,
                      code : menuCode,
                      text : menuName
                    });

                menu.add({
                      text : menuName,
                      menu : m
                    });
                createNestedMenu(m, menuCode)
              }
            }
          }
        });
  }

  // viewport 渲染后，加载子系统菜单项
  function successFn(response) {
    var data = Ext.decode(response.responseText);

    if (data != null && data.success) {
      var subSys = data.subSystems;
      for (var i = 0; i < subSys.length; i++) {
        var menuCode = subSys[i].resourceId;
        var menuName = subSys[i].text;

        var m = new Ext.menu.Menu({
              id : 'menu-' + subSys[i].resourceId,
              code : menuCode,
              // iconCls: 'bmenu', // <-- icon
              text : menuName
            });

        menuBar.add(new Ext.Toolbar.Separator());
        menuBar.add({
              text : menuName,
              // iconCls: 'bmenu', // <-- icon
              iconCls : subSys[i].iconCls,
              menu : m
            });
        createNestedMenu(m, menuCode);
      }

      menuBar.add(new Ext.Toolbar.Separator());
      var aboutMenu = new Ext.menu.Menu({
            id : 'about-menu',
            style : {
              overflow : 'visible'
            },
            items : [{
                  id : "menu-change-todo",
                  icon : 'resources/img/status2.gif',
                  text : '待办事项',
                  handler : function() {
                    // toMainPanelTab();
                    mainPanel.activate("welcome-panel");
                    /*
                     * Ext.Ajax.request({ method : "POST", url :
                     * "aaa_test/dubbo_test_1", callback : function(o, s, r) {
                     * var respText = Ext.decode(r.responseText); alert(123); }
                     * });
                     */
                  },
                  scope : this
                }, {
                  id : "menu-change-pwd",
                  icon : 'resources/img/key.gif',
                  text : '修改密码',
                  handler : function() {
                    pwdWin.show();
                  },
                  scope : this
                }, {
                  text : '关于',
                  handler : function() {
                    aboutWin.show();
                  },
                  scope : this
                }, {
                  text : '在线帮助',
                  handler : function() {
                  },
                  scope : this,
                  disabled : true
                }]
          });

      menuBar
          .add(
              {
                text : '帮助',
                icon : 'resources/img/help.gif',
                menu : aboutMenu
              },
              {
                id : "menu-logout2",
                icon : 'resources/img/icon/logoff.png',
                text : '注销',
                handler : function() {
                  doLogout();
                },
                scope : this
              },
              '->',
              '<span id="cur-db-name"></span>&nbsp;&nbsp;当前用户:&nbsp;&nbsp;<span id="cur-user-name">'
                  + sysConfig.user_name + '</span>');

      menuBar.doLayout();
    }

  }

  // 注销
  function doLogout() {
    Ext.Ajax.request({
          url : "common/logout",
          scope : this,
          callback : function(o, s, r) {
            var respText = Ext.decode(r.responseText);
            if (respText.success && respText.message == "OK") {
              viewport.destroy();
              window.location.href = 'common/index';
            } else {
              if (!Ext.isEmpty(respText.message)) {
                Ext.Msg.alert('错误', respText.message);
              } else {
                Ext.Msg.alert('错误', '因为不能取得服务端信息，不能正常注销。');
              }
            }
          }
        });
  }

  // 回到首页
  function goToIndex() {
    onCloseMainPanelTabs();
    window.location.href = 'common/index';
  }

  function getSysConfig() {
    if (sysConfig == null) {
      Ext.Ajax.request({
            url : "common/getsystemconfig",
            scope : this,
            async : false,
            callback : function(o, s, r) {
              var resp = Ext.decode(r.responseText);
              sysConfig = {
                user_name : resp.user_name,
                application_name : resp.application_name,
                vendor : resp.vendor,
                copyright : resp.copyright,
                run_mode : resp.run_mode,
                version : resp.version,
                website : resp.website,
                buildId : resp.buildId,
                module_name : resp.resource.text,
                module_id : resp.resource.resourceId
              }
            }
          });
    }
  }

  // 直接修改用户session中的partDB
  function directUpdate(dbcode) {
    Ext.Ajax.request({
          url : "system/update_user_db",
          method : 'POST',
          params : {
            dbcode : dbcode
          },
          async : false,
          scope : this,
          callback : function(o, s, r) {
            var respText = Ext.decode(r.responseText);
            if (respText.success) {

            }
          }
        });
  }

  // 弹出窗口，根据用户选择修改session中的partDB
  function updateBySelect(data) {

    SelectDatabaseWin = new Divo.app.SelectDatabaseWin({
          userDBs : data
        });
    SelectDatabaseWin.on('afterselect', function(dbname) {
          Ext.fly('cur-db-name').dom.innerHTML = "当前数据库:" + dbname;
        }, this);
    SelectDatabaseWin.on('noselect', function() {
          goToIndex();
        }, this);
    SelectDatabaseWin.show();
  }

  /* ----------------------- public方法 ----------------------- */
  return {
    init : function() {
      uiDcInc = new Ext.util.MixedCollection();
      initUiDcIncludes(uiDcInc);
      // 分开存放定义
      initUiDcIncludes2(uiDcInc);
      initUiDcIncludes3(uiDcInc);
      initUiDcIncludes4(uiDcInc);

      getSysConfig();
      createMenus();
      createViewport();
    }
  }
}();

Ext.onReady(Divo.app.Main.init, Divo.app.Main, true);
